package com.neudu.glsb.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.neudu.glsb.commons.JSONReturn;
import com.neudu.glsb.dto.EmployeeAttendanceVO;
import com.neudu.glsb.pojo.EmployeeAttendance;
import com.neudu.glsb.pojo.Employees;
import com.neudu.glsb.service.EmployeeAttendanceService;
import com.neudu.glsb.service.EmployeesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class EmployeeAttendanceController {
    @Autowired
    private JSONReturn jsonReturn;
    @Autowired
    private EmployeesService employeesService;
    @Autowired
    private EmployeeAttendanceService employeeAttendanceService;

    @PostMapping("checkIn")
    public Map<String, Object> checkIn(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        Integer adminUserId = (Integer) request.get("adminUserId");

        Employees employee = employeesService.getEmployeeByAdminUserId(adminUserId);
        if (employee == null) {
            result.put("success", false);
            result.put("message", "未找到该员工");
            return result;
        }

        // 关键修复：明确使用东八区（Asia/Shanghai）时间
        ZoneId beijingZone = ZoneId.of("Asia/Shanghai");
        LocalDateTime nowBeijingTime = LocalDateTime.now(beijingZone);

        EmployeeAttendance attendance = new EmployeeAttendance();
        attendance.setEmployeeId(employee.getId());
        // 转换为Date类型存入数据库（带时区信息）
        attendance.setAttendanceDate(Date.from(nowBeijingTime.atZone(beijingZone).toInstant()));
        attendance.setIsSigned(1);
        // 签到时间同样使用北京时间
        attendance.setSignInTime(Date.from(nowBeijingTime.atZone(beijingZone).toInstant()));

        // 检查是否迟到（以北京时间9点为基准）
        LocalTime nineAM = LocalTime.of(9, 0, 0);
        boolean isLate = nowBeijingTime.toLocalTime().isAfter(nineAM);

        attendance.setIsLate(isLate ? 1 : 0);
        employeeAttendanceService.addCheckInRecord(attendance);

        if (isLate) {
            result.put("success", true);
            result.put("message", employee.getEmployeeName() + "，签到成功，但你已迟到，下次早点");
        } else {
            result.put("success", true);
            result.put("message", employee.getEmployeeName() + "，签到成功");
        }
        return result;
    }

    @GetMapping("getLateCount")
    public Map<String, Object> getLateCount(@RequestParam Integer adminUserId) {
        Map<String, Object> result = new HashMap<>();

        Employees employee = employeesService.getEmployeeByAdminUserId(adminUserId);
        if (employee == null) {
            result.put("success", false);
            result.put("message", "未找到该员工");
            return result;
        }

        int lateCount = employeeAttendanceService.getLateCountByEmployeeId(employee.getId());
        result.put("success", true);
        result.put("count", lateCount);
        return result;
    }

    @PostMapping("getHistorySign")
    public Map<String, Object> getHistorySign(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        Integer adminUserId = (Integer) request.get("adminUserId");

        Employees employee = employeesService.getEmployeeByAdminUserId(adminUserId);
        if (employee == null) {
            result.put("success", false);
            result.put("message", "未找到该员工");
            return result;
        }

        List<EmployeeAttendance> historyList = employeeAttendanceService.getHistorySign(employee.getId());
        result.put("success", true);
        result.put("historyList", historyList);
        return result;
    }

    @PostMapping("get_all_attendance")
    public Map<String, Object> getAllAttendance(@RequestBody Map<String, Integer> params) {
        int pageNum = params.getOrDefault("pageNum", 1);
        int pageSize = params.getOrDefault("pageSize", 10);
        IPage<EmployeeAttendanceVO> page = employeeAttendanceService.getAllAttendance(pageNum, pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", page);
        return result;
    }
}
